// Forwarder.java
//
// ICS 22 / CSE 22 Winter 2010
// Project #2: You Won't Find Me There

import java.io.Console;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Scanner;

import javax.management.Query;
import javax.sound.midi.SysexMessage;

public class Forwarder {

	// You can use this scanner to read input from the console, one line
	// at a time.
	private Scanner input;
	private LinkedList<ForwardEntry> m_entries;
	private boolean m_running;

	// You'll probably find that you need to add other fields here

	public Forwarder() {
		input = new Scanner(System.in);
		m_entries = new LinkedList<ForwardEntry>();
		m_running = true;

	}

	private String getInput() {

		String in = input.nextLine();
		return in;
	}

	private void parseInput(String input) {
		if (input.compareTo("ADD") == 0) {
			// TODO fix multiple entries
			String name = getInput();
			String oldAd = getInput();
			String newAd = getInput();
			ForwardEntry temp = new ForwardEntry(name, oldAd, newAd);
			m_entries.addToFront(temp);
			System.out.println("Added\n");
		} else if (input.compareTo("MAIL") == 0) {
			String name = getInput();
			String ad = getInput();
			LinkedList<ForwardEntry>.Iterator it = m_entries.iterator();
			boolean done = false, sent = false;
			int count = 0;
			while (it.hasNext() && !done) {
				ForwardEntry temp = it.next();
				// check if the same name
				if (temp.getName().compareTo(name) == 0 && 
					// check if old address in the list entry equals, if so
					// send to the new address of the list entry
					ad.compareTo(temp.getOldAddress()) == 0) {
						System.out.println("Send to " + temp.getNewAddress()
								+ "\n");
						done = true;
						sent = true;
					
				}
				System.out.println("count:"+count+"\n"); 
				count++;

			}
			if (!sent) {
				System.out.println("Send to " + ad + "\n");
			}
		} else if (input.compareTo("REMOVE") == 0) {
			String name = getInput();
			String oldAd = getInput();
			String newAd = getInput();
			ForwardEntry temp = new ForwardEntry(name, oldAd, newAd);
			
//			try{
//				m_entries.remove(temp);
//			}catch(NoSuchElementException e){
//				System.out.println("No Entry");
//			}
		} else if (input.compareTo("QUIT") == 0) {
			System.out.println("Goodbye\n");
			m_running  = false;
		}
		else{
			System.out.println("Invalid input command\n");
		}
	}

	public void go() {
		while (m_running) {
			// System.in.read();
			parseInput(getInput());
		}
	}
}
